<template>
  <view>
	  <scroll-view scroll-y="true" style="height: 90vh;">
	<uni-forms ref="form" :modelValue="formData">
		<view class="form_list">
			<view class="input">
				<view><uni-icons type="link" size="22"></uni-icons>同步地址：</view>
				<uni-easyinput v-model="formData.url" :placeholderStyle="placeholderStyle"
				placeholder="请输入内容"></uni-easyinput>
			</view>
		</view>
		<view class="form_list">
			<view class="input">
				<view><uni-icons type="link" size="22"></uni-icons>外网地址：</view>
				<uni-easyinput v-model="formData.ourl" :placeholderStyle="placeholderStyle"
				placeholder="请输入内容"></uni-easyinput>
			</view>
		</view>
		<view class="form_list">
			<view class="input3">
				<view><uni-icons type="gear" size="22"></uni-icons>小数位数：</view>
				<uni-easyinput v-model="formData.qtyDecimal" trim="all" type="number" :placeholderStyle="placeholderStyle"
				placeholder="请输入小数位数"></uni-easyinput>
			</view>
		</view>
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载入库任务
				</view>
				<!-- <view>
					<uni-data-checkbox class="radio" v-model="formData.procure_cover" :localdata="cover_arr"></uni-data-checkbox>
				</view> -->
				<switch :style="style" :checked="formData.syn_procure==1?true:false" @change="switchPro" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载拣货任务
				</view>
				<!-- <view>
					<uni-data-checkbox class="radio" v-model="formData.material_cover" :localdata="cover_arr"></uni-data-checkbox>
				</view> -->
				<switch :style="style" :checked="formData.syn_appmaterial==1?true:false" @change="switchAppMaterial" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载物料档案
				</view>
				<view>
					<uni-data-checkbox class="radio" v-model="formData.inv_cover" :localdata="cover_arr"></uni-data-checkbox>
				</view>
				<switch :style="style" :checked="formData.syn_inventory==1?true:false" @change="switchInv" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载货架
				</view>
				<switch :style="style" :checked="formData.syn_shelves==1?true:false" @change="switchShelves" color="#18bc9c" />
			</view>
		</view>

		<!-- <view class="form_list">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="tune" size="22"></uni-icons> 货架物料分类策略
				</view>
				<switch :style="style" :checked="formData.syn_shelvesInvclass==1?true:false" @change="switchShelvesInvclass" color="#18bc9c" />
			</view>
		</view> -->
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载即时库存
				</view>
				<switch :style="style" :checked="formData.syn_kc==1?true:false" @change="switchKc" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list" v-show="formData.online==1?false:true">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="download" size="22"></uni-icons> 下载仓库
				</view>
				<switch :style="style" :checked="formData.syn_warehouse==1?true:false" @change="switchStk" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="clear" size="22"></uni-icons> 清空表结构
				</view>
				<switch :style="style" :checked="formData.delDbTab==1?true:false" @change="switchDeltab" color="#18bc9c" />
			</view>
		</view>
		
		<view class="form_list">
			<view class="list-detail">
				<view class="left">
					<uni-icons type="tune" size="22"></uni-icons> {{formData.online==0?'离线':'在线'}}模式
				</view>
				<switch :style="style" :checked="formData.online==1?true:false" @change="switchOnline" color="#18bc9c" disabled />
			</view>
		</view>
		
		<view class="form_list">
			<view class="list-detail" @click="toPage('/pages/config/dept_set')">
				<view><uni-icons type="gear" size="22"></uni-icons> 单据配置默认部门</view>
				<uni-icons type="forward" size="22"></uni-icons>
			</view>
		</view>
		
		<view class="swiper-button">
			<button @click="reset" v-show="username!='admin'?true:false">重置</button>
			<button @click="toset">
				{{username=='admin'?'初始化':'确认'}}
			</button>
		</view>
	 </uni-forms>
	 </scroll-view>
  </view>
</template>

<script>
// 引入uni-ui组件
import {
  uniEasyinput,
  uniForms,uniDataCheckbox
} from "@dcloudio/uni-ui"
export default {
  data() {
    return {
	  placeholderStyle:'font-size:17px;',
	  formData:{
		  online:1,//默认在线
		  inv_cover:0,//默认增量
		  material_cover:0,//默认增量
		  procure_cover:0,//默认增量
		  syn_shelvesInvclass:0,//默认关闭
		  qtyDecimal:2//默认小数位数
	  },
	  defaultData:{
		  //url:'http://192.168.0.209:8881',
		  //默认配置
		  url:'http://43.139.225.36:8890',
		  ourl:'http://183.233.224.166:18088',
		  syn_inventory:1,//物料档案
		  inv_cover:0,//默认增量
		  material_cover:1,//默认增量
		  procure_cover:1,//默认增量
		  syn_shelvesInvclass:0,//默认货架分类策略 关闭
		  syn_invShelvesLastest:0,//默认同步物料和货架关系（最近路径）
		  syn_kc:0,//库存
		  syn_warehouse:0,
		  syn_shelves:0,
		  syn_procure:0,
		  syn_appmaterial:0,
		  delDbTab:0,
		  online:1,//1在线，0离线
		  syn_filename_arr:[],
		  qtyDecimal:2//默认小数位数
	  },
	  style:'transform:scale(0.7)',
	  user:uni.getStorageSync('user'),
	  username:uni.getStorageSync('username'),
	  cover_arr: [{
	  	text: '增量',
	  	value: 0
	  },
	  {
	  	text: '覆盖',
	  	value: 1
	  }]
    }
  },
  components: {
	uniEasyinput,
	uniForms,uniDataCheckbox
  },
  onShow() {
  	uni.$off('downloadOK')
	if(uni.getStorageSync('myconfig')!=''){
		this.formData = uni.getStorageSync('myconfig')
	}
  },
  onLoad(){
	  if(!this.$Db.isOpen()){
	  	//打开数据库
	  	this.$Db.openSqlite()
	  }
	  
	  //this.$Db.dropTable('myconfig')
	  //自动创建我的配置表
	  this.$Db.queryIsTable('myconfig').then(res => {
	  	if(!res){
	  		this.$Db.createTable('myconfig','"content" TEXT')
	  		var content = JSON.stringify(this.defaultData);
	  		this.$Db.insertTableData('myconfig',"'"+content+"'").then(res=>{
				//默认配置
				this.formData = JSON.parse(content)
			})
	  	}else{
			this.$Db.selectTableData('myconfig').then(res=>{
				this.formData = JSON.parse(res[0].content);
			})
		}
	  });
	  
	  //user warehouse inventory_class
	  /* this.$Db.selectTableData('inventory_class').then(res=>{
	  	console.log(res )
	  }).catch(err=>{
	  	console.log(err)
	  }) */
	  //监听配置：初始化、修改
	  uni.$off('backMycnofig')
	  uni.$on('backMycnofig',(flag)=>{
		  if(flag){
			  setTimeout(()=>{
				  if(this.user!=''&&this.user!=null){
					  //用户设置保存，先停留在设置页
					  /* uni.navigateBack({
						url:'/pages/config/list'
					  }) */
				  }else{
					  uni.reLaunch({
						url:'/pages/config/list'
					  })
				  }
			  },1500)
		  }
	  })
  },
  methods: {
    async toset(){
		uni.showLoading({
			mask:true
		})
		let _this = this;
		let syn_filename_arr = []
		this.formData.syn_filename_arr = []
		
		//检测是否有用户日志表
		await this.$Db.queryIsTable('action_log').then(res => {
			if(!res){
				let sql = '"id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"userid"  TEXT,"username"  TEXT,"action"  TEXT,"url"  TEXT,"result"  TEXT,"syn_status" INTEGER DEFAULT 0,"create_date"  TEXT,"uuid"  TEXT';
				this.$Db.createTable('action_log',sql)
				console.log('action_log create ok')
			}
		}).catch(err=>{
			console.log(err)
		})
		
		await Object.keys(this.formData).forEach(key=>{
			  if(key.indexOf('syn_') === 0 && this.formData[key] === 1){
				  //需要同步的设置
				  let arr = key.split('_')
				  syn_filename_arr.push(arr[1])
			  }
		})
		
		if(syn_filename_arr.length>0){
			this.formData.syn_filename_arr = syn_filename_arr
		}
		
		await this.$Db.deleteTableData('myconfig');
		await this.$Db.insertTableData('myconfig',"'"+JSON.stringify(this.formData)+"'").then(res=>{
			uni.setStorageSync('myconfig',this.formData)
		});
		
		this.$Func.getDeviceInfo()//设置uuid标识
		//下载U8用户，json文件
		if(this.username == 'admin'){
			// await this.$Api.getJsonUrl('user').then(res => {
			// 	if(res.data.code == 1){
			// 		this.$Api.toCopy('user.json',res.data.data);
			// 	}else{
			// 		this.$Api.msg('user.json下载异常')
			// 	}
			// })
			//下载仓库，json文件
			// await this.$Api.getJsonUrl('warehouse').then(res => {
			// 	if(res.data.code == 1){
			// 		this.$Api.toCopy('warehouse.json',res.data.data);
			// 	}else{
			// 		this.$Api.msg('warehouse.json下载异常')
			// 	}
			// })
			//获取要执行的sql语句
			let sql_arr = []
			await this.$Api.getPcSql().then(res => {
				if(res.statusCode==200){
					if(res.data!=''&&res.data!=undefined){
						if(res.data.length>0){
							try{
								for(let sql of res.data){
									console.log(sql)
									if(sql=='create table'){
										//针对先删语句后，执行创建
										this.$Db.createPdaTable(false)
										this.$Db.addlog('admin执行create table成功','')
									}else{
										this.$Db.exeSQL(sql).then(res=>{
											this.$Db.addlog('admin执行sql成功',sql)
										})
									}
								}
							}catch(e){
								//TODO handle the exception
								this.$Db.addlog('admin执行sql异常',e)
							}
						}
					}
				}
			})
			
			//下载物料分类树
			/*await this.$Api.getJsonUrl('inventory_class').then(res => {
				if(res.data.code == 1){
					this.$Api.toCopy('inventory_class.json',res.data.data);
				}else{
					this.$Api.msg('inventory_class.json下载异常')
				}
			})*/
			setTimeout(() => {
				//单号表
				this.$Db.queryIsTable('mcode').then(res => {
					if(!res){
						//编号表
						var sql = '"date" TEXT,"type" TEXT,"number" INTEGER,"code" TEXT';
						this.$Db.createTable('mcode',sql);
						console.log('mcode create ok')
					}
				})
				
				this.$Db.selectTableData('warehouse').then(ress => {
					// this.$Db.deleteTableData('warehouse')//先清空
					// //没数据,则新增
					// this.$Api.getJsonContent('warehouse').then(res => {
					// 	 let warehouse = JSON.parse(res);//总数组
					// 	 warehouse.forEach((m) => {
					// 		 let sql = '"'+m.id+'","'+m.name+'","'+m.number+'",""';
					// 		_this.$Db.insertTableData('warehouse',sql).catch(err=>{
					// 			console.log(err)
					// 		});
					// 	 });
					// 	 console.log('warehouse insert ok')
					// }).catch(err=>{
					// 	console.log(err)
					// })
				}).catch(err=>{
					console.log(err)
				})
				
				//检查是否有用户表，没则创建
				// this.$Db.queryIsTable('user').then(res => {
				// 	if(res){
				// 		//清空用户
				// 		this.$Db.deleteTableData('user')
				// 		this.$Db.selectTableData('user').then(ress => {
				// 			//没数据,则新增
				// 			this.$Api.getJsonContent('user').then(res => {
				// 				 let user = JSON.parse(res);//总数组
								 
				// 				 user.forEach((m) => {
				// 					 /* _this.$Db.selectTableData('user','userid',m.userid).then(user_res => {
				// 						 if(user_res.length == 0){}
				// 					 }) */
				// 					 let psd = '000000'
				// 					 let remark = ''
				// 					 if(m.psd!=undefined){
				// 						 psd = m.psd
				// 					 }
				// 					 if(m.remark!=undefined){
				// 					 	remark = m.remark
				// 					 }
				// 					 let sql = '"'+m.userid+'","'+m.username+'","'+m.nickname+'","'+psd+'","","'+remark+'"';
									 
				// 					 _this.$Db.insertTableData('user',sql);
				// 				 });
				// 				 console.log('user insert ok')
				// 				 _this.$Api.msg('设置完成','success')
				// 				 uni.$emit('backMycnofig',true)
				// 				 uni.hideLoading()
				// 			}).catch(err=>{
				// 				console.log(err)
				// 			})
				// 		})
				// 	}
				// }).catch(err=>{
				// 	console.log(err)
				// })
				//console.log('user insert ok')
				this.$Api.msg('设置完成','success')
				uni.$emit('backMycnofig',true)
				uni.hideLoading()
			},2000)
		}else{
			this.$Api.msg('设置完成','success')
			uni.$emit('backMycnofig',true)
			uni.hideLoading()
		}
    },
	switchPro: function (e) {
		this.formData.syn_procure = 0;
		if(e.detail.value){
			this.formData.syn_procure = 1;
		}
	},
	switchAppMaterial: function (e) {
		this.formData.syn_appmaterial = 0;
		if(e.detail.value){
			this.formData.syn_appmaterial = 1;
		}
	},
	switchInv: function (e) {
		this.formData.syn_inventory = 0;
		if(e.detail.value){
			this.formData.syn_inventory = 1;
		}
	},
	switchKc: function (e) {
		this.formData.syn_kc = 0;
		if(e.detail.value){
			this.formData.syn_kc = 1;
		}
	},
	switchStk: function (e) {
		this.formData.syn_warehouse = 0;
		if(e.detail.value){
			this.formData.syn_warehouse = 1;
		}
	},
	switchUser: function (e) {
		this.formData.syn_user = 0;
		if(e.detail.value){
			this.formData.syn_user = 1;
		}
	},
	switchShelves: function (e) {
		this.formData.syn_shelves = 0;
		if(e.detail.value){
			this.formData.syn_shelves = 1;
		}
	},
	switchShelvesInvclass: function (e) {
		this.formData.syn_shelvesInvclass = 0;
		if(e.detail.value){
			this.formData.syn_shelvesInvclass = 1;
		}
	},
	switchDeltab:function (e) {
		this.formData.delDbTab = 0;
		if(e.detail.value){
			this.formData.delDbTab = 1;
		}
	},
	switchOnline:function (e) {
		this.formData.online = 0
		if(e.detail.value){
			this.formData.online = 1
			this.formData.syn_inventory = 0
			this.formData.syn_warehouse = 0
			this.formData.syn_kc = 0
			this.formData.syn_shelves = 0
			this.formData.syn_procure = 0
			this.formData.syn_appmaterial = 0
			this.formData.syn_invShelvesLastest = 0
		}
	},
	reset(){
		let _this = this
		uni.showModal({
			title: "确定要重置配置?", 
			content: "",
			success: (res) => {
				if (res.confirm) {
					_this.$Db.deleteTableData('myconfig').then(()=>{
						_this.formData = _this.defaultData
						_this.toset()
					}).catch(err=>{
						_this.$Api.msg(err)
					})
				}
			},
		})
	},
	toPage(url){
		uni.showLoading({
			mask:true
		})
		uni.navigateTo({
			url:url,
		})
		uni.hideLoading()
	},
  }
}
</script>
<style lang="less">
	.radio{
		padding-left: 40rpx;
	}
	.left{
		width:400rpx;
	}
</style>